<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>3列表排序</title>
    <script src="../js/vue.js"></script>
</head>
<body>
    <!-- 
        想对数据加工后再展示
     -->
    <div id="root">
        <h2>明星列表</h2>
        <input v-model="keyWord" type="text" placeholder="请输入明星姓名">
        <button @click="sortType = 1">年龄升序↑</button>
        <button @click="sortType = 2">年龄升序↓</button>
        <button @click="sortType = 0">原顺序</button>
        <ul>
            <li v-for="(p,index) in fmtPersons" :key="p.id">
                {{p.name}}--{{p.sex}}--{{p.age}}岁
            </li>
        </ul>
    </div>

    <script>
        new Vue({
            el: '#root',
            data: {
                keyWord: '',
                sortType: 0, //0 代表不排序 1 升序 2 降序
                persons: [
                    {id: '001', name: '温兆伦', sex: '男', age: 33},
                    {id: '002', name: '周杰伦', sex: '男', age: 21},
                    {id: '003', name: '周冬雨', sex: '女', age: 45},
                    {id: '004', name: '马冬梅', sex: '女', age: 32},
                    {id: '006', name: '千千', sex: '女', age: 43},
                    {id: '005', name: '吴千语', sex: '女', age: 36},
                ]
            },
            computed: {
                fmtPersons(){
                    const {persons, keyWord, sortType} = this
                    let arr =  persons.filter(p => p.name.indexOf(keyWord) !== -1)
                    //排序 sort方法 改变原数组
                    if(sortType){
                        //排序
                        arr.sort((a, b) => {
                            if(sortType === 1) return a.age - b.age
                            else return b.age - a.age
                        })
                    }
                    return arr

                }
            }
            //在watch修改原数据 会导致原数据的丢失
            // watch: {
            //     keyWord(value){
            //        const arr = this.persons.filter(p => p.name.indexOf(value) !== -1)
            //        console.log(arr);
            //         this.persons = arr;
            //     }
            // }
           
        })
    </script>
</body>
</html>